
PLUG.Platform = PLUG_PLATFORM_SERVER

PLUG.ClassName = "sv_limits"
PLUG.PrintName = "Serverside Entity Limits"
PLUG.Author = "thomasfn"

function PLUG:Init()
	self:LoadLimits()
	self:EnforceLimits()
end

function PLUG:LoadLimits()
	self.Limits = plugs.Call( "ReadLimits" ) or {}
end

function PLUG:EnforceLimits()
	for _, v in pairs( self.Limits ) do
		local cvar = "sbox_max" .. v[1]
		game.ConsoleCommand( cvar .. " " .. tostring( v[2] ) .. "\n" )
	end
end

function PLUG:SetLimit( id, limit )
	local f
	for _, v in pairs( self.Limits ) do
		if (id == v[1]) then
			v[2] = tonumber( limit )
			f = true
		end
	end
	if (!f) then table.insert( self.Limits, { id, tonumber( limit ) } ) end
	local cvar = "sbox_max" .. id
	game.ConsoleCommand( cvar .. " " .. tostring( limit ) .. "\n" )
end

function PLUG:GetLimit( id )
	for _, v in pairs( self.Limits ) do
		if (v[1] == id) then return v[2] end
	end
	return 0
end

function PLUG:GetLimits()
	return self.Limits
end

function PLUG:DataStreamSV( pl, tbl )
	if (tbl[1] == "limit_change") then
		if (!pl:HasPriv( "changelimits" )) then return self:Err( "You do not have enough privileges to do that!" ) end
		local changer = tbl[2]
		if ((!changer) || (#changer == 0)) then return true end
		for _, v in pairs( changer ) do
			local id = v[1]
			local val = v[2]
			if (id && val) then
				self:SetLimit( id, val )
				pl:Log( "limits", "Changed " .. id .. " to " .. tostring( val ) )
			end
		end
		plugs.Call( "SaveLimits" )
		pl:PrintMessage( HUD_PRINTTALK, "Limits changed!" )
		return true
	end
end

function PLUG:Err( ply, text )
	ply:PrintMessage( HUD_PRINTTALK, text )
	return true
end